package com.woniuxy.service.impl;

import com.woniuxy.mapper.UserMapper;
import com.woniuxy.service.UserService;
import com.woniuxy.entity.UserEntity;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 马宇航
 * @Description: TODO
 * @DateTime: 25/10/23/星期四 10:35
 * @Component: 成都蜗牛学苑
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Cacheable(value = "user::findAll",key ="#root.targetClass" )//key： user::findAll
    @Tool(name = "userFindAll",description = "查询所有用户信息")
    public List<UserEntity> findAll() {
//        //先判断缓存有没有数据，如果有，则直接取redis中的数据
//        if (redisTemplate.hasKey("users::all")) {
//            return (List<UserEntity>) redisTemplate.opsForValue().get("users::all");
//        }else {
            List<UserEntity> all = userMapper.findAll();
//            redisTemplate.opsForValue().set("users::all", all);
            return all;
        }


    @Override
    //当查询的id>2才 缓存起来
    @Tool(description = "根据id查询用户信息")
    @Cacheable(value = "user",key = "#id",condition = "#id>20") //key 可以根据入参来作为变量，当作redis的key, user::1
    public UserEntity findById(@ToolParam(description = "用户id",required = true) int id) {
        return userMapper.findById(id).get();
    }

    @Override
    @CacheEvict(value = "user::findAll",key ="#root.targetClass")//删除user::findAll缓存
    public void delete(Integer id) {
        userMapper.deleteById(id);
    }


    @Override
    public UserEntity insert(UserEntity user) {
        //双删解决
        redisTemplate.delete("users::all");
        UserEntity save = userMapper.save(user);
        //插入数据成功，就要删掉缓存，更新用户，也要删缓存（面试题，缓存双删问题）
        if (save != null) {
            redisTemplate.delete("users::all");
        }
        return save;
    }
}
